using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;
using System.IO;

namespace SlamCms.SharePoint.UserManagement.Features
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("dcc0d30d-d0a1-4dce-908f-d9ede1f153b9")]
    public class SlamCmsUserManagementEventReceiver : SPFeatureReceiver
    {
        private static string _owner = "SLAMCMSUserManagement";
        private SPWebConfigModification[] _modifications = {
			
			new SPWebConfigModification() { 
				Name = "add[@name='UserGroupSynchronizeModule']", 
				Owner = _owner, 
				Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode, 
				Path = "/configuration/system.web/httpModules", 
				Value = "<add name=\"UserGroupSynchronizeModule\" type=\"SlamCms.SharePoint.UserManagement.UserGroupSynchronizeModule, SlamCms.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2fbc3f2db29fdc61\" />"},
			new SPWebConfigModification() { 
				Name = "add[@name='UserGroupSynchronizeModule']", 
				Owner = _owner, 
				Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode, 
				Path = "/configuration/system.webServer/modules", 
				Value = "<add name=\"UserGroupSynchronizeModule\" preCondition=\"integratedMode\" type=\"SlamCms.SharePoint.UserManagement.UserGroupSynchronizeModule, SlamCms.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2fbc3f2db29fdc61\" /> "},
		};

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication application = (SPWebApplication)properties.Feature.Parent;
			var configDirectory = FindConfigurationDirectory(application.IisSettings[SPUrlZone.Default].Path);
			string slamConfigPath = Path.Combine(application.IisSettings[SPUrlZone.Default].Path.FullName, "slam.config");
			if (configDirectory != null)
			{
				slamConfigPath = Path.Combine(configDirectory.FullName, "slam.config");
			}

			SPWebConfigModification slamConfigPathModification = new SPWebConfigModification()
			{
				Name = "add[@key='Slam.ConfigurationManager.Config']",
				Owner = _owner,
				Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
				Path = "/configuration/appSettings",
				Value = "<add key=\"Slam.ConfigurationManager.Config\" value=\"" + slamConfigPath + "\" />"
			};

            foreach (SPWebConfigModification modification in _modifications)
            {
                application.WebConfigModifications.Add(modification);
            }
			application.WebConfigModifications.Add(slamConfigPathModification);

            application.WebService.ApplyWebConfigModifications();
            application.Update();

        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication application = (SPWebApplication)properties.Feature.Parent;

            List<SPWebConfigModification> modificationsToRemove = new List<SPWebConfigModification>();
            foreach (SPWebConfigModification modification in application.WebConfigModifications)
            {
                if (modification.Owner == _owner)
                {
                    modificationsToRemove.Add(modification);
                }
            }

            foreach (SPWebConfigModification modification in modificationsToRemove)
            {
                application.WebConfigModifications.Remove(modification);
            }
            application.WebService.ApplyWebConfigModifications();
            application.Update();
        }

		private static DirectoryInfo FindConfigurationDirectory(DirectoryInfo currentDirectory)
		{
			DirectoryInfo configurationDirectory = null;
			currentDirectory = currentDirectory.Parent;

			if (currentDirectory != null && currentDirectory.Exists)
			{
				foreach (var childDirectory in currentDirectory.GetDirectories())
				{
					if (childDirectory.Name.Equals("config", StringComparison.OrdinalIgnoreCase) && configurationDirectory == null)
					{
						configurationDirectory = childDirectory;
						break;
					}
				}

				if (configurationDirectory == null)
				{
					configurationDirectory = FindConfigurationDirectory(currentDirectory);
				}
			}

			return configurationDirectory;
		}
    }
}
